// 引用加密函数
var bcrypt = require('./bcrypt.js')
var jwt = require('./jwt.js')

var dbmodel = require('../model/dbmodel.js');
var user = dbmodel.model('users');
var friend = dbmodel.model('friend');
var group = dbmodel.model('group');
var groupUser = dbmodel.model('groupUser');
var message = dbmodel.model('message');
var groupMessage = dbmodel.model('groupMsg');

exports.findUser = function(res) {
	user.find(function(err, val) {
		if (err) {
			console.log('查找失败', err);
		} else {
			res.send(val);
		}
	})
}

// 用户注册
exports.buildUser = function(name, mail, pws, res) {
	//密码加密
	let password = bcrypt.encryption(pws);

	let data = {
		name: name,
		email: mail,
		psw: password,
		register: new Date(),
	}

	// node大小写敏感，要区分User和user
	let User = new user(data);

	User.save(function(err, result) {
		if (err) {
			res.send(err);
		} else {
			res.send({
				status: 200
			});
		}
	})
}

//匹配用户表相同元素个数
exports.countUserValue = function(data, type, res) {
	let wherestr = {};
	// wherestr = {type:data}
	wherestr[type] = data;

	user.countDocuments(wherestr, function(err, result) {
		if (err) {
			res.send(err)
		} else {
			res.send({
				status: 200,
				is: result
			});
		}
	})
}

// 用户验证
exports.userMatch = function(data, pwd, res) {
	let wherestr = {
		$or: [{
			'name': data
		}, {
			'email': data
		}]
	};
	let out = {
		'name': 1,
		"imgurl": 1,
		'psw': 1
	}

	user.find(wherestr, out, function(err, result) {
		if (err) {
			res.send({
				status: 500
			});
		} else {
			if (result == '') {
				res.send({
					status: 404
				})
			}
			result.map(function(e) {
				const pwdMatch = bcrypt.verification(pwd, e.psw);
				if (pwdMatch) {
					let token = jwt.createToken(e._id)
					let back = {
						id: e._id,
						name: e.name,
						imgurl: e.imgurl,
						token: token
					}
					res.send({
						status: 200,
						back
					})
				} else {
					res.send({
						status: 400
					})
				}
			})
		}
	})
}

//用户搜索
exports.searchUser = function(data, res) {
	var wherestr
	if (data == 'yike') {
		wherestr = {}
	} else {
		wherestr = {
			$or: [{
				'name': {
					$regex: data
				}
			}, {
				'email': {
					$regex: data
				}
			}]
		};
	}
	let out = {
		'name': 1,
		"imgurl": 1,
		'email': 1
	}
	user.find(wherestr, out, function(err, result) {
		if (err) {
			res.send({
				status: 500
			})
		} else {
			res.send({
				status: 200,
				result
			})
		}
	})
}

//判断是否为好友
exports.isFriend = function(uid, fid, res) {
	let wherestr = {
		'userID': uid,
		'friendID': fid,
		state: 0
	};

	friend.findOne(wherestr, function(err, result) {
		if (err) {
			res.send({
				status: 500
			})
		} else {
			if (result) {
				res.send({
					status: 200,
					result
				})
			} else {
				res.send({
					status: 404
				})
			}
		}
	})
}

//搜索群
exports.searchGroup = function(data, res) {
	let wherestr;
	if (data = 'yike') {
		wherestr = {};
	} else {
		wherestr = {
			'name': {
				$regex: data
			}
		};
	}
	let out = {
		'name': 1,
		"imgurl": 1
	}
	group.find(wherestr, out, function(err, result) {
		if (err) {
			res.send({
				status: 500
			})
		} else {
			res.send({
				status: 200,
				result
			})
		}
	})
}

//判断是否在群里
exports.isInGroup = function(uid, gid, res) {
	let wherestr = {
		'userID': uid,
		'groupID': gid
	};

	groupUser.findOne(wherestr, function(err, result) {
		if (err) {
			res.send({
				status: 500
			})
		} else {
			if (result) {
				res.send({
					status: 200
				})
			} else {
				res.send({
					status: 404
				})
			}
		}
	})
}

// 用户详情
exports.userDetail = function(id,res){
	let wherestr = {'_id':id};
	let out = {'psw':0};
	user.findOne(wherestr,out,function(err,result){
		if(err){
			res.send({status:500});
		}else{
			res.send({status:200,result});
		}
	})
}

// 用户信息更改
exports.userUpdate = function(data,res){
	let updatestr = {}
	
	// 判断是否修改密码
	if(typeof(data.pwd)!='undefined'){
		// 匹配密码
		user.find({'_id':data.id},{'psw':1},function(err,result){
			if(err){
				res.send({status:500});
			}else{
				result.map(function(e){
					const pwdMatch = bcrypt.verification(data.pwd,e.psw);
					if(pwdMatch){
						updatestr[data.type]=bcrypt.encryption(data.data);
						user.findByIdAndUpdate(data.id,updatestr,function(err,result){
							if(err){
								res.send({status:500});
							}else{
								res.send({status:200});
							}
						})
					}else{
						res.send({status:400})
					}
				})
			}
		})
	}else{
		updatestr[data.type]=data.data;
		user.findByIdAndUpdate(data.id,updatestr,function(err,result){
			if(err){
				res.send({status:500});
			}else{
				res.send({status:200});
			}
		})
	}
}

// 获取好友昵称
exports.getMarkName = function(data,res){
	let wherestr = {'userID':data.uid,'friendID':data.fid};
	let out = {'markname':1};
	friend.findOne(wherestr,out,function(err,result){
		if(err){
			res.send({status:500});
		}else{
			res.send({status:200,result})
		}
	})
}

// 修改好友昵称
exports.changeMarkName = function(data,res){
	let wherestr = {'userID':data.uid,'friendID':data.fid};
	let updatestr = {'markname':data.name};
	friend.updateOne(wherestr,updatestr,function(err,result){
		if(err){
			res.send({status:500});
		}else{
			res.send({status:200})
		}
	})
}

// 添加好友
exports.buildFriend = function(uid,fid,state,res){
	let data = {
		userID:uid,
		friendID:fid,
		state:state,
		time:new Date()
	}
	
	let Friend = new friend(data)
	
	Friend.save(function(err,result){
		if(err){
			console.log('buildFriend err')
		}else{
			console.log('buildFriend success')
		}
	})
}

// 一对一消息
exports.innerMsg = function(uid,fid,msg,type,res){
	let data = {
		userID:uid,
		friendID:fid,
		message:msg,
		type:type,
		time:new Date(),
		state:0
	}
	
	let Msg = new message(data)
	
	Msg.save(function(err,result){
		if(err){
			console.log('innerMsg err')
		}else{
			console.log('innerMsg success')
		}
	})
}

// 好友申请
exports.addFriend = function(data,res){
	let wherestr = {'userID':data.uid,'friendID':data.fid};
	friend.countDocuments(wherestr,(err,result) => {
		if(err){
			res.send({status:500})
		}else{
			if(result == 0){
				this.buildFriend(data.uid,data.fid,1);
			}else{
				friend.updateOne(wherestr,{'tiem':new Date()},function(err,result){
					if(err){
						res.send({status:500});
					}else{
						res.send({status:200})
					}
				})
			}
			this.innerMsg(data.uid,data.fid,data.msg,0)
		}
	})
}

// 同意好友
exports.agreeFriend = function(data,res){
	let wherestr = {$or:[{'userID':data.uid,'friendID':data.fid},{'userID':data.fid,'friendID':data.uid}]};
	friend.updateMany(wherestr,{'state':0},function(err,result){
		if(err){
			res.send({status:500});
		}else{
			res.send({status:200})
		}
	})
}

// 拒绝好友
exports.disagreeFriend = function(data,res){
	let wherestr = {$or:[{'userID':data.uid,'friendID':data.fid},{'userID':data.fid,'friendID':data.uid}]};
	friend.updateMany(wherestr,{'state':2},function(err,result){
		if(err){
			res.send({status:500});
		}else{
			res.send({status:200})
		}
	})
}

// 获取用户列表
exports.getUserList = function(data,res){
	let query = friend.find({});
	// 查询条件
	query.where({'userID':data.uid,'state':data.state});
	// 查找friendID的关联集合 user
	query.populate('friendID');
	// 排序方式 time倒序
	query.sort({'time':-1});
	// 查询结果
	query.exec().then(function(e){
		let result = e.map(function(res){
			return {
				id:res.friendID._id,
				name:res.friendID.name,
				imgurl:res.friendID.imgurl,
				markname:res.markname,
				time:res.time
			}
		})
		res.send({status:200,result});
	}).catch(function(err){
		res.send({status:500,err})
	})
}

// 获取一对一消息
exports.getMessage = function(data,res){
	let query = message.findOne({});
	// 查询条件
	query.where({$or:[{'userID':data.uid,'friendID':data.fid},{'userID':data.fid,'friendID':data.uid}]});
	// 排序方式 time倒序
	query.sort({'time':-1});
	// 查询结果
	query.exec().then(function(e){
		let result =  {
				type:res.type,
				message:res.message,
				time:res.time
			}
		res.send({status:200,result});
	}).catch(function(err){
		res.send({status:500,err})
	})
}

// 获取未读消息数
exports.unreadMsg = function(data,res){
	let wherestr = {'userID':data.uid,'friendID':data.fid,'state':1};
	message.countDocuments(wherestr,(err,result) => {
		if(err){
			res.send({status:500,err})
		}else{
			res.send({status:200,result})
		}
	})
}

// 未读消息数修改
exports.updateReadMsg = function(data,res){
	let wherestr = {'userID':data.uid,'friendID':data.fid,'state':1};
	let updatestr = {'state':0}
	message.updateMany(wherestr,updatestr,(err,result) => {
		if(err){
			res.send({status:500})
		}else{
			res.send({status:200})
		}
	})
}

// 获取群列表
exports.getGroupList = function(data,res){
	let query = groupUser.find({});
	// 查询条件
	query.where({'groupID':data.gid});
	// 查找groupID的关联集合 group
	query.populate('groupID');
	// 排序方式 time 倒序
	query.sort({'time':-1});
	// 查询结果
	query.exec().then(function(e){
		let result = e.map(function(res){
			return {
				gid:res.groupID._id,
				name:res.groupID.name,
				imgurl:res.groupID.imgurl,
				time:res.time,
				tip:res.tip
			}
		})
		res.send({status:200,result});
	}).catch(function(err){
		res.send({status:500,err})
	})
}

// 获取群消息
exports.getGroupMessage = function(data,res){
	let query = groupMessage.findOne({});
	// 查询条件
	query.where({'groupID':data.gid});
	// 查找userID的关联集合 user
	query.populate('userID');
	// 排序方式 time倒序
	query.sort({'time':-1});
	// 查询结果
	query.exec().then(function(e){
		let result =  {
				type:res.type,
				message:res.message,
				time:res.time,
				name:res.userID.name
			}
		res.send({status:200,result});
	}).catch(function(err){
		res.send({status:500,err})
	})
}

// 群未读消息数修改
exports.updateReadGroupMsg = function(data,res){
	let wherestr = {'userID':data.uid,'groupID':data.gid};
	let updatestr = {'tip':0}
	message.updateMany(wherestr,updatestr,(err,result) => {
		if(err){
			res.send({status:500})
		}else{
			res.send({status:200})
		}
	})
}